package cn.falconnect.adserver.adapter.persistence.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.falconnect.adserver.enumration.OS;

/**
 * mybatis 枚举对象映射。OS 枚举映射 typeHandler=*.class
 * @author wangwei
 *
 * @param <E>
 */
public class OSEnumTypeHandler extends BaseTypeHandler<List<OS>> {
	private static Logger logger = LoggerFactory.getLogger(OSEnumTypeHandler.class);

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, List<OS> parameter, JdbcType jdbcType)
			throws SQLException {
		// TODO 待完成。
		
	}

	@Override
	public List<OS> getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String i = rs.getString(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
        	return getObject(i);
        }
	}

	@Override
	public List<OS> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String i = rs.getString(columnIndex);
	        if (rs.wasNull()) {
	            return null;
	        } else {
	        	return getObject(i);
	        }
	}
	

	@Override
	public List<OS> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		// TODO 待完成。
		return null;
	}
	
	 /**
     * 从数据库获得值映射为Enum
     * @param key
     * @return
     */
    private List<OS> getObject(String key){
    	try {
			if(StringUtils.isEmpty(key)){
				return null;
			}
			String[] results = key.split(",");
			List<OS> list = new ArrayList<>();
			for(String k:results){ 
				Integer i = Integer.valueOf(k);
				OS os = OS.osMap.get(i);
				if(os!=null){
					list.add(os);
				}
			}
			return list;
		} catch (NumberFormatException e) {
			logger.error("枚举映射失败!",e);
			return null;
		}
    }

}
